<template>
  <BasicModal
    title="添加成员"
    :destroy-on-close="true"
    width="60%"
    @ok="handleSubmit"
    @register="registerModal"
  >
    <BasicTable @register="register" />
  </BasicModal>
</template>
<script setup lang="ts">
  import { BasicModal, useModal } from '@/components/Modal';
  import { BasicTable, FormSchema, useTable } from '@/components/Table/';
  import { ref } from 'vue';
  import { userListExcludeRoleId, saveUserRole } from '@/api/sys/rbac';
  import { message } from 'ant-design-vue';

  const emits = defineEmits(['success']);
  const tableColumns = [
    {
      title: '用户名',
      dataIndex: 'userName',
    },
    {
      title: '姓名',
      dataIndex: 'realName',
    },
    {
      title: '手机号',
      dataIndex: 'mobilePhone',
    },
    {
      title: '操作',
      dataIndex: '__ACTION__',
      width: 120,
    },
  ];
  const searchFormSchemas: FormSchema[] = [
    {
      label: '用户名',
      field: 'm_LIKE_userName',
      component: 'Input',
      colProps: { span: 6 },
      componentProps: {
        placeholder: '请输入用户名',
      },
    },
    {
      label: '姓名',
      field: 'm_LIKE_realName',
      component: 'Input',
      colProps: { span: 6 },
      componentProps: {
        placeholder: '请输入姓名',
      },
    },
    {
      label: '手机号',
      field: 'm_LIKE_mobilePhone',
      component: 'Input',
      colProps: { span: 6 },
      componentProps: {
        placeholder: '请输入手机号',
      },
    },
  ];
  const currentRecord = ref();
  const mSelectedRowKeys = ref<any>([]);
  const [registerModal, { openModal }] = useModal();
  const [register, { reload }] = useTable({
    rowKey: 'id',
    showIndexColumn: false,
    useSearchForm: true,
    formConfig: {
      labelWidth: 80,
      schemas: searchFormSchemas,
    },
    api: userListExcludeRoleId,
    columns: tableColumns,
    beforeFetch: (params) => {
      return {
        ...params,
        roleId: currentRecord.value.id,
      };
    },
    rowSelection: {
      type: 'checkbox',
      onChange(selectedRowKeys) {
        mSelectedRowKeys.value = selectedRowKeys;
      },
    },
    customRow: undefined,
  });
  const handleSubmit = () => {
    if (mSelectedRowKeys.value.length === 0) {
      message.error('请选择要添加的成员');
      return;
    }
    saveUserRole(
      mSelectedRowKeys.value.map((userId) => {
        return {
          roleId: currentRecord.value.id,
          userId: userId,
        };
      }),
    ).then(() => {
      message.success('提交成功');
      mSelectedRowKeys.value = [];
      emits('success');
      reload();
    });
  };

  defineExpose({
    show(record) {
      currentRecord.value = record;
      openModal();
    },
  });
</script>
